// 云函数入口文件
const cloud = require('wx-server-sdk')
var request = require('request-promise')
const fs = require('fs')
const path = require('path')

cloud.init()

// 云函数入口函数
exports.main = async (event, context) => {
  let url = ""
  switch (event.action) {
    case "beauty":
      let file2 = path.join(__dirname, 'beautys.json');
      let result2 = JSON.parse(fs.readFileSync(file2, 'utf-8'));
      return result2;
      break;
    case "chbqb":
      let file1 = path.join(__dirname, 'chbqb.json');
      let result1 = JSON.parse(fs.readFileSync(file1, 'utf-8'));
      return result1;
      break;
    case "chapters":
      // url = "https://wanandroid.com/wxarticle/chapters/json"
      let file = path.join(__dirname, 'menu.json');
      let result = JSON.parse(fs.readFileSync(file, 'utf-8'));
      return result;
      break;
    case "history":
      let menuKey = event.key ? `?k=${event.key}` : ''
      url = `https://wanandroid.com/wxarticle/list/${event.menuId}/${event.pageNum}/json${menuKey}`
      break
    case "popular":
      url = `https://www.wanandroid.com/article/list/${event.pageNum}/json`
      break
    case "getHtmlData":
      url = `http://81.68.145.189:3000/demo/getWeiXinHtml?url=${event.url}`
      break
  }
  if (url) {
    return getJsonData(url)
  } else {
    return "參數錯誤"
  }
}

// 獲取JSON數據
async function getJsonData(url) {
  var res = request(url).then(html => {
    return JSON.parse(html);
  }).catch(err => {
    console.log(err);
  })
  return res
}
